package com.podcstr.filter;

import com.podcstr.qualifier.CurrentSession;
import com.podcstr.session.UserSession;

import javax.inject.Inject;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author azim
 * @since 5/20/13 
 */
public class LoginFilter implements Filter {

    private FilterConfig filterConfig;

    @Inject
    @CurrentSession
    private UserSession userSession;

    @Override
    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        String requestedUri = ((HttpServletRequest) req).getRequestURI();

        if (userSession == null || userSession.getUser() == null) {

            if (requestedUri.contains("login_") || requestedUri.contains("logout")) {
                ((HttpServletResponse) resp).sendRedirect("loginform.xhtml");
            } else {
                chain.doFilter(req, resp);
            }

        } else if (userSession != null && userSession != null) {

            if (requestedUri.contains("loginform") || requestedUri.contains("create_user")) {
                ((HttpServletResponse) resp).sendRedirect("index.xhtml");
            } else {
                chain.doFilter(req, resp);
            }
        } else {
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

        this.filterConfig = config;
    }

}
